package org.breathe.command.impl.set;

import org.breathe.command.Command;
import org.breathe.command.CommandType;
import org.breathe.datastruct.RedisBytes;
import org.breathe.datastruct.RedisData;
import org.breathe.datastruct.impl.RedisSet;
import org.breathe.protocal.Resp;
import org.breathe.protocal.decode.BulkString;
import org.breathe.protocal.decode.RespInteger;
import org.breathe.server.core.RedisCore;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: breathe
 * @createTime: 2025-05-13
 */
public class SAdd implements Command {
    private RedisCore redisCore;
    private RedisBytes key;
    private List<RedisBytes> members;
    public SAdd(RedisCore redisCore) {
        this.redisCore = redisCore;
    }
    @Override
    public CommandType getType() {
        return CommandType.SADD;
    }

    @Override
    public void setContext(Resp[] array) {
        key = ((BulkString)array[1]).getContent();
        members = Stream.of(array)
                .skip(2)
                .map(BulkString.class::cast)
                .map(BulkString::getContent)
                .collect(Collectors.toList());
    }

    @Override
    public Resp handle() {
        RedisSet redisSet = null;
        RedisData redisData = redisCore.get(key);
        if (redisData == null) {
            redisSet = new RedisSet();
        } else {
            redisSet = (RedisSet) redisData;
        }
        int add = redisSet.add(members);
        redisCore.put(key, redisSet);
        return new RespInteger(add);
    }

    @Override
    public boolean writeCommand() {
        return true;
    }
}
